package com.axjy.item.service.impl;

import com.axjy.item.service.IndexFloorService;
import com.axjy.item.vo.*;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service("indexFloorService")
public class IndexFloorServiceImpl implements IndexFloorService {

    @Resource
    private RedissonClient redissonClient;

    @Override
    public List<IndexFloorItems> queryFloorItems() {
        RMap<FloorKeyVo, List<ItemVo>> map = redissonClient.getMap("tp:item:floor");
        List<IndexFloorItems> list = map.keySet().stream().map(floorKeyVo -> {
            IndexFloorItems indexFloorItems=new IndexFloorItems();
            BeanUtils.copyProperties(floorKeyVo,indexFloorItems);
            List<ItemVo> itemVos = map.get(floorKeyVo);
            List<FloorItemVo> floorItemVoList = itemVos.stream().map(itemVo -> {
                FloorItemVo vo = new FloorItemVo();
                BeanUtils.copyProperties(itemVo,vo);
                return vo;
            }).collect(Collectors.toList());
            indexFloorItems.setItems(floorItemVoList);
            return indexFloorItems;
        }).sorted((a,b)->a.getFloor()-b.getFloor()).collect(Collectors.toList());
        return list;
    }

    @Override
    public ItemDetailVo queryItemDetail(Integer id) {
        //根据tp:item:floor得到一个map
        RMap<FloorKeyVo, List<ItemVo>> map = redissonClient.getMap("tp:item:floor");
        //================================================================
        //对map进行转换
        ItemVo result = null;
        for (List<ItemVo> list:map.values()){
            Optional<ItemVo> optional = list.stream().filter(itemVo -> id.equals(itemVo.getId()))
                    .findFirst();
            if(optional.isPresent()){
                result = optional.get();
                break;
            }
        }
        //result查询的结果拷贝道ITemDetailVo然后吧ItemDetailVo进行返回
        ItemDetailVo itemDetailVo= new ItemDetailVo();
        BeanUtils.copyProperties(result,itemDetailVo);
        return itemDetailVo;
        }
    }